<template>
  <view class="orders">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <text class="back" @click="goBack">＜</text>
      <text class="nav-title">我的订单</text>
      <image class="nav-logo" src="/static/logo.png" mode="aspectFit" />
    </view>

    <!-- 标签页 -->
    <view class="tabs">
      <view v-for="(tab, idx) in tabs" :key="tab" :class="['tab', currentTab === idx ? 'active' : '']" @click="switchTab(idx)">{{ tab }}</view>
    </view>

    <!-- 订单列表 -->
    <scroll-view
      class="order-list"
      scroll-y="true"
      :style="{ height: scrollHeight + 'px' }"
      @scrolltolower="loadMore"
      :lower-threshold="100"
    >
      <view class="order-card" v-for="(item, idx) in filteredOrders" :key="item.id || idx" @click="goOrderDetail(item)">
        <view class="order-header">
          <text class="order-no">订单号：{{ item.orderNo }}</text>
          <text class="order-date">{{ item.createTime }}</text>
        </view>
        <view class="order-body">
          <view class="order-row">
            <text class="label">辅导项目：</text>
            <view class="type-btn">{{ getTutoringItemText(item.tutoringItem) }}</view>
            <view class="spacer"></view>
            <text class="label">预算区间：</text>
            <text class="budget">{{ formatBudget(item.budgetMin, item.budgetMax) }}</text>
          </view>
          <view class="order-row">
            <text class="label">学生：</text>
            <text class="student-name">{{ item.studentName || '学生' }}</text>
            <view class="spacer"></view>
            <text class="label">专业：</text>
            <text class="major">{{ item.studyMajor }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="loadingMore" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!pagination.hasMore && filteredOrders.length > 0" class="no-more-state">
        <text class="no-more-text">没有更多订单了</text>
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && filteredOrders.length === 0" class="empty-state">
        <text class="empty-text">暂无相关订单</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { orderApi, constants } from '../../../api'

// 教师端订单状态：投递中、已拒绝、交付中、已完成
const tabs = ['投递中', '已拒绝', '交付中', '已完成']
const currentTab = ref(0)
const scrollHeight = ref(600)
const loading = ref(false)
const loadingMore = ref(false)
const orderList = ref([])
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
  hasMore: true
})

// 标签页对应的投递状态值
const tabStatusMap = {
  0: constants.TEACHER_DELIVERY_STATUS.DELIVERING,  // 投递中
  1: constants.TEACHER_DELIVERY_STATUS.REJECTED,    // 已拒绝
  2: constants.TEACHER_DELIVERY_STATUS.IN_DELIVERY, // 交付中
  3: constants.TEACHER_DELIVERY_STATUS.COMPLETED    // 已完成
}

// 模拟教师端订单数据（保留作为备用）
const teacherOrders = ref([
  {
    id: 'FD13455555333',
    no: 'FD13455555333',
    date: '2025-3-12 12:11:12',
    type: '作业',
    budget: '1000-2000元',
    studentName: '张同学',
    major: '数学',
    status: 0, // 0:投递中 1:已拒绝 2:交付中 3:已完成
    description: '需要完成高等数学作业，包含微积分和线性代数部分',
    stage: '本科',
    location: '国内',
    school: '北京大学'
  },
  {
    id: 'FD13455555334',
    no: 'FD13455555334',
    date: '2025-3-11 15:30:45',
    type: '论文',
    budget: '3000-5000元',
    studentName: '李同学',
    major: '计算机',
    status: 2, // 交付中
    description: '需要计算机专业毕业论文指导，主要是算法优化方面',
    stage: '本科',
    location: '国内',
    school: '清华大学'
  },
  {
    id: 'FD13455555335',
    no: 'FD13455555335',
    date: '2025-3-10 09:15:30',
    type: '作业',
    budget: '1500-2500元',
    studentName: '王同学',
    major: '英语',
    status: 3, // 已完成
    description: '英语作业辅导，包括语法修正、写作指导和口语练习',
    stage: '本科',
    location: '国内',
    school: '复旦大学'
  },
  {
    id: 'FD13455555336',
    no: 'FD13455555336',
    date: '2025-3-09 14:20:15',
    type: '保研',
    budget: '2000-3000元',
    studentName: '刘同学',
    major: '经济学',
    status: 1, // 已拒绝
    description: '需要保研面试指导，包括简历修改和面试技巧培训',
    stage: '本科',
    location: '国内',
    school: '上海财经大学'
  }
])

// 计算属性，按tab筛选订单
const filteredOrders = computed(() => {
  return orderList.value
})

// 加载教师端订单列表
const loadOrderList = async (isRefresh = false) => {
  if (loading.value && isRefresh) return
  if (loadingMore.value && !isRefresh) return

  if (isRefresh) {
    loading.value = true
  } else {
    loadingMore.value = true
  }

  try {
    const delverStatus = tabStatusMap[currentTab.value]

    const params = {
      current: isRefresh ? 1 : pagination.value.current,
      size: pagination.value.size,
      delverStatus: delverStatus
    }

    const response = await orderApi.getTeacherOrderList(params)

    if (response.code === '1000') {
      const result = response.result
      if (isRefresh) {
        orderList.value = result.records || []
        pagination.value.current = 1
      } else {
        orderList.value = [...orderList.value, ...(result.records || [])]
      }

      pagination.value.total = result.total || 0
      pagination.value.current = result.current || 1
      pagination.value.hasMore = (result.current || 1) < (result.pages || 0)
    } else {
      uni.showToast({
        title: response.message || '加载失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'error'
    })
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多数据
const loadMore = async () => {
  if (!pagination.value.hasMore || loadingMore.value) return

  pagination.value.current += 1
  await loadOrderList(false)
}

// 切换标签页
const switchTab = (index) => {
  if (currentTab.value === index) return

  currentTab.value = index
  pagination.value.current = 1
  orderList.value = []
  loadOrderList(true)
}

// 获取辅导项目文本
const getTutoringItemText = (item) => {
  return constants.TUTORING_ITEM_TEXT[item] || '未知'
}

// 格式化预算区间
const formatBudget = (min, max) => {
  return `${min}-${max}元`
}

const goBack = () => {
  uni.navigateBack()
}

const goOrderDetail = (order) => {
  // 根据订单状态跳转到不同的详情页面
  let detailPageUrl = ''
  switch (order.status) {
    case 0: // 投递中
      detailPageUrl = './PendingOrderDetail'
      break
    case 1: // 已拒绝
      detailPageUrl = './RejectedOrderDetail'
      break
    case 2: // 交付中
      detailPageUrl = './InProgressOrderDetail'
      break
    case 3: // 已完成
      detailPageUrl = './CompletedOrderDetail'
      break
    default:
      detailPageUrl = './PendingOrderDetail'
  }

  uni.navigateTo({
    url: detailPageUrl + '?order=' + encodeURIComponent(JSON.stringify(order))
  })
}

onMounted(() => {
  // 计算滚动区域高度
  const systemInfo = uni.getSystemInfoSync()
  scrollHeight.value = systemInfo.windowHeight - 200 // 减去导航栏和标签栏高度

  // 加载初始数据
  loadOrderList(true)
})
</script>

<style scoped>
.orders {
  min-height: 100vh;
  background: #f8f8f8;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 32rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.back {
  font-size: 36rpx;
  color: #333;
  padding: 0 16rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
}

.nav-logo {
  width: 60rpx;
  height: 60rpx;
}

/* 标签页 */
.tabs {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab.active {
  color: #1e98d7;
  font-weight: bold;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #1e98d7;
  border-radius: 2rpx;
}

/* 订单列表 */
.order-list {
  flex: 1;
  padding: 20rpx;
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.order-no {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.order-date {
  font-size: 24rpx;
  color: #999;
}

.order-body {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.order-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16rpx;
}

.label {
  font-size: 26rpx;
  color: #666;
}

.type-btn {
  background: #e8f4fd;
  color: #1e98d7;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.spacer {
  flex: 1;
}

.budget {
  font-size: 26rpx;
  color: #ff6b35;
  font-weight: bold;
}

.student-name {
  font-size: 26rpx;
  color: #333;
}

.major {
  font-size: 26rpx;
  color: #666;
}

.description {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  margin-top: 8rpx;
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 没有更多数据状态 */
.no-more-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
}

.no-more-text {
  font-size: 28rpx;
  color: #ccc;
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
